<?php
namespace frontend\models;

use common\models\WechatUser;
use Yii;
use common\models\SmsForm;
use yii\base\Model;
use common\models\User;

/**
 * Signup form
 */
class SignupForm extends Model
{
    use \common\traits\Model;
    
    public $mobile;
    public $group_id;
    public $code;
    
    private $_user;
    

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['mobile', 'code'], 'required'],
            [['mobile'], 'integer'],
            ['mobile', 'match', 'pattern' => Yii::$app->params['match']['mobile']],
            ['code', 'validateCode'],
        ];
    }
    
    public function attributeLabels(){
        return [
            'mobile' => '手机号',
            'code' => '验证码',
        ];
    }
    
    /**
     * 验证验证码是否正确
     * @param $attribute
     * @return bool|void
     */
    public function validateCode($attribute)
    {
        if( !$this->hasErrors() ){
            $model = new SmsForm(['mobile' => $this->mobile]);
            if( !$model->validateCode($this->code) ){
                return $this->addError($attribute, '验证码不正确');
            }
        }
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {
        if (!$this->validate()) {
            return null;
        }
        
        $model = $this->getUser();
        $model->mobile = $this->mobile;
        $model->group_id = $this->group_id ?: 1;
        $model->save();
        return $model->save() ? $model : false;
    }
    
    /**
     * @return User|null
     */
    protected function getUser()
    {
        if( $this->_user === null ){
            $wechatUser = Yii::$app->wechat->getUser()->original;
            // 添加开发测试信息
            if( YII_ENV_DEV && empty($user) ){
//                $wechatUser = WechatUser::findOne(['openid' => 'oCveNwqG0NE1fkA6Ovj2l3UvStHQ']);
            }
            $user= WechatUser::createOauth($wechatUser);
            $this->_user = $user->getMember($this->mobile);
        }
        return $this->_user;
    }
    
}
